package com.gscitysfy.cus.drain.modules.duty.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gscitysfy.cloudfrmwk.assistant.domain.Result;
import com.gscitysfy.cloudfrmwk.portal.feign.DictionaryService;
import com.gscitysfy.cloudfrmwk.portal.feign.UserService;
import com.gscitysfy.cloudfrmwk.portal.vo.UserInfoVO;

import com.gscitysfy.cus.drain.constants.DicConstant;
import com.gscitysfy.cus.drain.modules.duty.entity.MoperDutyMnPeople;
import com.gscitysfy.cus.drain.modules.duty.entity.MoperDutyMnPeopleExcel;
import com.gscitysfy.cus.drain.modules.duty.entity.MoperDutyMnRota;
import com.gscitysfy.cus.drain.modules.duty.mapper.MoperDutyMnPeopleMapper;
import com.gscitysfy.cus.drain.modules.duty.mapper.MoperDutyMnRotaMapper;
import com.gscitysfy.cus.drain.modules.duty.service.IMoperDutyMnPeopleService;
import com.gscitysfy.cus.drain.utils.HttpResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author 葛守跃
 * @version 1.0.0
 * @ClassName MoperDutyMnPeopleServiceImpl
 * @Description 值班人员管理实现类
 * @creatTime 2022-03-31 10:56:13
 */
@Service
@Slf4j
public class MoperDutyMnPeopleServiceImpl extends ServiceImpl<MoperDutyMnPeopleMapper, MoperDutyMnPeople> implements IMoperDutyMnPeopleService {

    @Resource
    private MoperDutyMnPeopleMapper peopleMapper;

    @Resource
    private UserService userService;

    @Resource
    private DictionaryService dictionaryService;

    @Resource
    private MoperDutyMnRotaMapper moperDutyMnRotaMapper;

    /**
     * 条件查询值班人员列表
     *
     * @param page
     * @param people
     * @return
     */
    @Override
    public IPage<MoperDutyMnPeople> getDutyPeopleListByCondition(Page<MoperDutyMnPeople> page, MoperDutyMnPeople people) {
        return peopleMapper.getDutyPeopleListByCondition(page, people);
    }

    /**
     * 添加值班人员
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addDutyPerson(String ids) {
       Result<List<UserInfoVO>> userInfoByIds = userService.getUserInfoByIds(Arrays.asList(ids.split(StrUtil.COMMA)));
        List<UserInfoVO> userList = userInfoByIds.getData();
        if (!CollUtil.isEmpty(userList)) {
            final List<String> idList = new ArrayList<>(16);
            userList.forEach(item -> {
                MoperDutyMnPeople people = this.copyProperties(item);
                if (!checkUserExist(people)) {
                    people.setCoamUsable(0L);
                    this.saveOrUpdate(people);
                    idList.add(people.getCoamKid());
                }
            });
            return CollUtil.join(idList, StrUtil.COMMA);
        }
        return StrUtil.EMPTY;
    }

    /**
     * 检验用户是否已经存在
     *
     * @param people
     * @return
     */
    private boolean checkUserExist(MoperDutyMnPeople people) {
        LambdaQueryWrapper<MoperDutyMnPeople> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MoperDutyMnPeople::getCoamPersonId, people.getCoamPersonId())
        .eq(MoperDutyMnPeople::getCoamUsable,0L);
        return this.count(queryWrapper) > 0;
    }

    /**
     * 拷贝字段
     *
     * @param user
     * @return
     */
    private MoperDutyMnPeople copyProperties(UserInfoVO user) {
        MoperDutyMnPeople people = new MoperDutyMnPeople();
        people.setCoamPersonId(user.getUserId());
        people.setCoamPersonUsername(user.getName());
        people.setCoamPersonGender(user.getGender());
        people.setCoamPersonContactNumber(user.getPhoneNumber());
        people.setCoamPersonLoginAccount(user.getUserName());
        people.setCoamPersonAccountStatus(user.getPbfStatus());
        people.setCoamPersonRole(user.getJob());
        return people;
    }

    /**
     * 根据条件导出值班人员
     * @param people
     */
    @Override
    public void exportDutyPerson(HttpServletResponse response, MoperDutyMnPeople people) throws IOException {
        List<MoperDutyMnPeopleExcel> dutyPeopleExcelList = peopleMapper.getDutyPeopleExcelList(people);
        Map<String, String> dutyTypeMap = dictionaryService.getDictionaryMap(DicConstant.DUTY_TYPE).getData();
        Map<String, String> sysFlagMap = dictionaryService.getDictionaryMap(DicConstant.SYSTEM_FLAG).getData();
        Map<String, String> genderMap = dictionaryService.getDictionaryMap(DicConstant.GENDER_TYPE).getData();

        dutyPeopleExcelList.forEach(item -> {
            item.setCoamSysFlag(sysFlagMap.get(item.getCoamSysFlag()));
            item.setCoamPersonType(dutyTypeMap.get(item.getCoamPersonType()));
            item.setCoamPersonGender(genderMap.get(item.getCoamPersonGender()));
        });
        String fileName = "值班人员列表.xlsx";
        HttpResponseUtil.setResponseHeaders(response, fileName);
        EasyExcel.write(response.getOutputStream(), MoperDutyMnPeopleExcel.class)
                .sheet("值班人员列表")
                .doWrite(() -> dutyPeopleExcelList);
    }

    @Override
    public List<MoperDutyMnPeople> selectEnableAutoDutyPeople() {
        return list(
                Wrappers.<MoperDutyMnPeople>lambdaQuery()
                        .eq(MoperDutyMnPeople::getCoamUsable, DicConstant.UN_DELETE)
                        .eq(MoperDutyMnPeople::getCoamAutodutyFlag, MoperDutyMnPeople.AUTO_DUTY)
                        .eq(MoperDutyMnPeople::getCoamDutyState, DicConstant.ENABLE.toString())
        );
    }

    /**
     * 删除值班人员
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByIds(String ids){
        String separate = ",";
        for (String id : ids.split(separate)){
            MoperDutyMnPeople people = peopleMapper.selectById(id);
            Wrapper<MoperDutyMnRota> peopleWrapper = new LambdaQueryWrapper<MoperDutyMnRota>()
                    .eq(MoperDutyMnRota::getCoamDutyPersonId, people.getCoamPersonId());
            List<MoperDutyMnRota> moperDutyMnRotas = moperDutyMnRotaMapper.selectList(peopleWrapper);
            if (CollectionUtils.isNotEmpty(moperDutyMnRotas)) {
                return false;
            }
        }
        for (String id : ids.split(separate)){
            MoperDutyMnPeople people = new MoperDutyMnPeople();
            people.setCoamKid(id);
            people.setCoamUsable(1L);
            peopleMapper.updateById(people);
        }
        return true;
    }

    /**
     * 获取调班人员列表
     * @param people
     * @return
     */
    @Override
    public List<MoperDutyMnPeople> getExchangePeopleListByCondition(MoperDutyMnPeople people) {
        //值班班次
        MoperDutyMnRota rota = new MoperDutyMnRota();
        rota.setCoamClassesId(people.getCoamClassesId());
        rota.setCoamGenerateDate(people.getCoamGenerateDate());
        List<MoperDutyMnPeople> peopleList = this.moperDutyMnRotaMapper.getDutyPersonByDateAndClasses(rota);

        //替班班次
        rota.setCoamClassesId(people.getCoamExchangeClassesId());
        rota.setCoamGenerateDate(people.getCoamExchangeGenerateDate());

        List<MoperDutyMnPeople> exchangePeopleList = this.moperDutyMnRotaMapper.getDutyPersonByDateAndClasses(rota);

        //如果有交集
        for (MoperDutyMnPeople moperDutyMnPeople : CollUtil.intersection(peopleList, exchangePeopleList)) {
            if(people.getCoamPersonId().equals(moperDutyMnPeople.getCoamPersonId())){
                return Collections.emptyList();
            }
        }
        //如果没有交集
        exchangePeopleList.removeAll(peopleList);
        return exchangePeopleList;
    }

    @Override
    public String updateDutyPersonByUserInfoVO(UserInfoVO user) {
        if(StringUtils.isNotEmpty(user.getUserId())){
            String userId = user.getUserId();
            List<MoperDutyMnPeople> moperDutyMnPeopleList = peopleMapper.selectList(Wrappers.<MoperDutyMnPeople>lambdaQuery()
                    .eq(MoperDutyMnPeople::getCoamPersonId, userId));
            if(CollectionUtils.isNotEmpty(moperDutyMnPeopleList)){
                for(MoperDutyMnPeople moperDutyMnPeople:moperDutyMnPeopleList){
                    this.copyProperties(moperDutyMnPeople, user);
                    peopleMapper.updateById(moperDutyMnPeople);
                }
            }
        }
        return null;
    }


    /**
     * 拷贝字段
     *
     * @param user
     * @return
     */
    private MoperDutyMnPeople copyProperties(MoperDutyMnPeople people,UserInfoVO user) {
        people.setCoamPersonId(user.getUserId());
        people.setCoamPersonUsername(user.getName());
        people.setCoamPersonGender(user.getGender());
        people.setCoamPersonContactNumber(user.getPhoneNumber());
        people.setCoamPersonLoginAccount(user.getUserName());
        people.setCoamPersonAccountStatus(user.getPbfStatus());
        people.setCoamPersonRole(user.getJob());
        return people;
    }
}
